package jmind.core.serialize;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * description: java序列化之Hessian
 * https://www.jianshu.com/p/6a36dd1fcca8
 * @author weibo.xie
 * @date : create in 5:04 下午 2021/5/13
 */
public class HessianSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output output = new Hessian2Output(os);
        output.writeObject(object);
        output.close();
        byte[] bytes = os.toByteArray();
        os.close();
      return bytes;
    }

    @Override
    public Object deserialize(byte[] bytes) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Hessian2Input input=null;
        try {
             input = new Hessian2Input(bis);
            return input.readObject();
        }finally {
            if(input!=null)
                input.close();
            bis.close();
        }
    }
}